<template>
	<view class="container">
		<!-- #ifdef MP -->
		<view class="fixed z-1000" :style="[appletStyle]" v-if="myApplet">
			<view class="myApplet w-324 h-62 text-center rd-12rpx lh-62rpx fs-24 bg--w111-fff text-w111-303133">
				点击添加到我的小程序
				<text class="iconfont icon-ic_close2 text--w111-ccc ml-16" @click="myApplet = false"></text>
			</view>
		</view>
		<!-- #endif -->

		<!-- 固定顶部栏（无背景色） -->
		<view class="top-bar" :style="{ top: safeTop + 'px' }">
			<!-- 不跳转商城主页 -->
			<!-- <view class="menu-btn" @click="goToProfile">
				<image src="/static/base/index/store-w.png" class="menu-icon" mode="aspectFit" />
			</view> -->
			<!-- <image @click="changePerson" src="/static/base/index/change.png" style="position: absolute;left: 65px;"
				class="menu-icon" mode="aspectFit" /> -->
			<text class="page-title"></text>
			<view class="top-right">
			</view>
		</view>

		<!-- 可滚动内容区域 -->
		<scroll-view @scroll="onScroll" scroll-y class="content" style="height: calc(100vh);">
			<!-- 新品推荐轮播图 -->
			<view class="swiper-container">
				<text class="first-title" :style="{ top: safeTop + 'px' }">新品推荐</text>

				<swiper :indicator-dots="false" :autoplay="true" :interval="3000" :duration="500"
					@change="onSwiperChange" class="swiper">
					<swiper-item v-for="(item, index) in swiperList" :key="index" class="swiper-item">
						<image :src="item.image" class="swiper-image" mode="aspectFill" />
						<view class="swiper-content">
							<text class="main-title">{{ item.title }}</text>
							<text class="sub-title">{{ item.subtitle }}</text>
						</view>
					</swiper-item>
				</swiper>

				<!-- 固定悬浮按钮 -->
				<view class="fixed-buttons">
					<view class="button" @click="moreProducts">更多商品</view>
					<view class="button" @click="viewDetails">了解详情</view>
				</view>

				<!-- 指示器 -->
				<view class="swiper-dots">
					<view v-for="(dot, index) in swiperList.length" :key="index" class="dot"
						:class="{ active: currentIndex === index }"></view>
				</view>
			</view>

			<!-- 热门推荐 -->
			<view class="section">
				<text class="section-title">热门推荐</text>
				<scroll-view scroll-x class="horizontal-scroll" @scroll="onHotScroll" scroll-with-animation
					ref="hotScrollView">
					<view class="product-grid">
						<view v-for="(item, index) in hotProducts" :key="index" class="product-item"
							@click="goToProductDetail(item.id)">
							<image :src="item.image" class="product-image" mode="aspectFill" />
							<text class="product-name">{{ item.name }}</text>
							<text class="product-price">¥{{ item.price }}</text>
						</view>
					</view>
				</scroll-view>

				<!-- 动态进度条 -->
				<!-- <view class="progress-container">
					<view class="progress-bar" :style="{ width: hotProgress + '%' }"></view>
				</view> -->

				<view class="view-more" @click="goToProductList">查看更多 <image class="more-icon"
						src="/static/base/more.svg"></image>
				</view>
			</view>

			<!-- 共创中心 -->
			<view class="section">
				<text class="section-title">共创中心</text>
				<!-- <scroll-view scroll-x
					style="white-space: nowrap;width: 100%;margin: 0rpx 10rpx;padding: 0 52.1rpx;margin-bottom: 50rpx;"
					:show-scrollbar="false" @scroll="handleScroll">
					<view
						style="display: inline-block; width: 280rpx; margin-right: 20rpx;overflow: hidden;"
						v-for="(item, index) in creativeWorks.slice(0, 4)" :key="index"
						@click="goToCreativeDetail(item.id)">
						<image :src="item.image || '/static/base/empty.png'" style="width: 100%;height: 400rpx"
							mode="aspectFill" />
						<view class="creative-title" style="margin-right: 5rpx;">{{ item.title }}</view>
						<view class="creative-meta">
							<image :src="item.avatar" class="avatar" mode="aspectFill" />
							<text class="author">{{ item.author }}</text>
						</view>
					</view>
				</scroll-view> -->
				<view class="creative-grid">
					<view v-for="(item, index) in creativeWorks.slice(0, 4)" :key="index" class="creative-item"
						@click="goToCreativeDetail(item.id)">
						<image :src="item.image || '/static/base/empty.png'" class="creative-image" mode="aspectFill" />
						<text class="creative-title">{{ item.title }}</text>
						<view class="creative-meta">
							<image :src="item.avatar" class="avatar"
								mode="aspectFill" />
							<text class="author">{{ item.author }}</text>
						</view>
					</view>
				</view>
				
				<view class="view-more" @click="goToCreativeList">探索更多 <image class="more-icon"
						src="/static/base/more.svg"></image>
				</view>
				
				<view style="height: 120rpx;width: 100%;"></view>
			</view>
		</scroll-view>

		<!-- 底部导航栏 -->
		<TableBar :current="0" :messagecount="messagecount" v-if="scrollTop > 40"/>
		<!-- <TableBar :current="0" :messagecount="messagecount"/> -->
	</view>
</template>

<script>
	import TableBar from '@/components/base/table-bar/Index.vue'
	import {
		getUnreadMessage
	} from '@/api/base/message.js'
	import {
		getProductslist,
		getProductHot // 新增导入
	} from '@/api/store.js'
	// 引入你的作品接口
	import {
		getWorkList
	} from '@/api/base/index.js' // 请根据实际路径调整
	import {
		mapGetters
	} from 'vuex'

	export default {
		computed: {
			...mapGetters(['isLogin']),
			// #ifdef MP
			appletStyle() {
				return {
					top: (this.getHeight.menuButtonInfo.bottom + 8) + 'px',
					right: '10px'
				};
			},
			// #endif
		},

		components: {
			TableBar
		},
		data() {
			return {
				scrollTop: 0,
				messagecount: 0,
				getHeight: this.$util.getWXStatusHeight(),
				myApplet: true,
				safeTop: 0,
				hotProgress: 100,
				currentIndex: 0,
				swiperList: [],
				hotProducts: [],
				// 初始为空，等待接口加载
				creativeWorks: []
			}
		},
		onLoad() {
			const {
				barTop
			} = this.$util.getWXStatusHeight();
			this.safeTop = barTop + 10;
			
			//三个方法，均不需要登录
			this.fetchNewProducts();
			this.fetchHotProducts();
			this.fetchCreativeWorks(); // 加载共创作品
		},

		onShow() {
			// #ifdef MP
			if (wx.canIUse('checkIsAddedToMyMiniProgram')) {
				this.checkMyApplet();
			} else {
				this.myApplet = true;
			}
			// #endif

			//登录后才加载未读消息
			if (this.isLogin) {
				this.initMessage()
			}

		},

		onPageScroll(e) {
			// #ifdef MP
			if (e.scrollTop > 20 && this.myApplet) {
				this.myApplet = false;
			}
			// #endif
		},

		methods: {
			onScroll(e){
				console.log(e.detail)
				this.scrollTop = e.detail.scrollTop
			},
			initMessage() {
				getUnreadMessage().then(res => {
					if (res.status === 200) {
						this.messagecount = res.data.like + res.data.comment
					} else(err => {
						uni.showToast({
							title: '获取数据失败',
							icon: 'none'
						})
						console.log('获取数据失败', err);
					})
				}).catch(err => {
					console.log('获取数据失败', err);
				})
			},
			checkMyApplet() {
				// #ifdef MP
				if (wx.canIUse && wx.canIUse('checkIsAddedToMyMiniProgram')) {
					wx.checkIsAddedToMyMiniProgram({
						success: (res) => {
							this.myApplet = !res.added;
						},
						fail: () => {
							this.myApplet = true;
						}
					});
				}
				// #endif
			},

			// 获取新品推荐商品（使用 getProductslist + news=1）
			async fetchNewProducts() {
				try {
					const res = await getProductslist({
						sid: 0,
						news: 1,
						page: 1,
						limit: 5
					});
					if (res.status === 200 && Array.isArray(res.data)) {
						this.swiperList = res.data.map(item => ({
							id: item.id,
							image: item.image,
							title: item.store_name.length > 6 ? item.store_name.substring(0, 6) : item
								.store_name,
							subtitle: '官网甄选'
						}));
					}
				} catch (error) {
					console.error('新品推荐加载失败:', error);
				}
			},

			// 获取热门推荐商品（使用 getProductHot 接口）
			async fetchHotProducts() {
				try {
					const res = await getProductHot(1, 4); // 一页4个，按设计
					if (res.status === 200 && Array.isArray(res.data)) {
						this.hotProducts = res.data.map(item => ({
							id: item.id,
							name: item.store_name.length > 6 ? item.store_name.substring(0, 6) : item
								.store_name,
							price: item.price,
							image: item.image
						}));
						// 进度条逻辑（若数量 <=3 则满进度）
						this.hotProgress = this.hotProducts.length <= 3 ? 100 : 0;
					}
				} catch (error) {
					console.error('热门推荐加载失败:', error);
				}
			},

			// 新增：获取共创作品列表
			async fetchCreativeWorks() {
				try {
					// keyword 不传
					const res = await getWorkList('', 1, 4, 0, 1);
					if (res.status === 200 && Array.isArray(res.data.list)) {
						this.creativeWorks = res.data.list.map(item => {
							let firstImage = '';
							if (Array.isArray(item.images) && item.images.length > 0) {
								firstImage = item.images[0];
							}
							return {
								id: item.id,
								title: item.title || '无标题',
								author: item.nickname || '匿名',
								image: firstImage,
								avatar: item.avatar
							};
						});
					}
				} catch (error) {
					console.error('共创作品加载失败:', error);
					this.creativeWorks = [];
				}
			},

			onHotScroll(e) {
				let scrollLeft, scrollWidth, clientWidth;

				// #ifdef H5
				const el = this.$refs.hotScrollView.$el;
				scrollLeft = el.scrollLeft;
				scrollWidth = el.scrollWidth;
				clientWidth = el.clientWidth;
				// #endif

				// #ifdef MP
				const detail = e.detail;
				scrollLeft = detail.scrollLeft;
				scrollWidth = detail.scrollWidth;
				clientWidth = detail.clientWidth;
				// #endif

				const maxScroll = scrollWidth - clientWidth;
				if (maxScroll <= 0) {
					this.hotProgress = 100;
					return;
				}
				const progress = (scrollLeft / maxScroll) * 100;
				this.hotProgress = Math.min(100, Math.max(0, progress));
			},

			onSwiperChange(e) {
				this.currentIndex = e.detail.current;
			},

			goToProfile() {
				uni.navigateTo({
					url: '/pages/index/index'
				});
			},

			//热门推荐商品
			goToProductList() {
				uni.navigateTo({
					url: `/pages/base/goods_list_new/index?type=1`
				});
			},

			goToProductDetail(id) {
				uni.navigateTo({
					url: `/pages/goods_details/index?id=${id}`
				});
			},

			goToCreativeList() {
				uni.navigateTo({
					url: '/pages/sub_base/creative-list/index'
				});
			},

			goToCreativeDetail(id) {
				uni.navigateTo({
					url: `/pages/sub_base/creative-detail/index?id=${id}`
				});
			},
			//新品推荐页
			moreProducts() {
				uni.navigateTo({
					url: `/pages/base/goods_list_new/index?type=2`
				});
			},

			viewDetails() {
				if (this.swiperList.length === 0) {
					uni.showToast({
						title: '暂无商品',
						icon: 'none'
					});
					return;
				}
				const currentProduct = this.swiperList[this.currentIndex];
				if (currentProduct && currentProduct.id) {
					uni.navigateTo({
						url: `/pages/goods_details/index?id=${currentProduct.id}`
					});
				} else {
					uni.showToast({
						title: '商品信息异常',
						icon: 'none'
					});
				}
			}
		}
	}
</script>

<style scoped>
	.horizontal-scroll {
		white-space: nowrap;
		overflow-x: auto;
	}



	.container {
		min-height: 100vh;
		/* background-color: #F2F8FC; */
		background-color: white;
		overflow: hidden;
		position: relative;
	}

	.myApplet {
		position: relative;
	}

	.myApplet::after {
		position: absolute;
		right: 55px;
		top: -5px;
		content: '';
		width: 0;
		height: 0;
		border-left: 7px solid transparent;
		border-right: 7px solid transparent;
		border-bottom: 7px solid #fff;
	}

	.more-icon {
		width: 23rpx;
		height: 23rpx;
		margin-left: 2rpx;
	}

	/* 顶部无背景栏 */
	.top-bar {
		position: fixed;
		left: 0;
		right: 0;
		height: 48.6rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 27.8rpx;
		z-index: 100;
		background: transparent;
	}

	.menu-btn {
		width: 76.3rpx;
		height: 76.3rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.menu-icon {
		width: 48rpx;
		height: 48rpx;
	}

	.page-title {
		font-size: 34.7rpx;
		font-weight: 500;
		color: #ffffff;
	}

	.top-right {
		display: flex;
		align-items: center;
	}

	/* 内容区域 */
	.content {
		height: calc(100vh - 34.7rpx);
		position: relative;
		width: 100%;
		overflow-y: auto;
	}

	/* 新品推荐轮播图 */
	.swiper-container {
		position: relative;
		height: 100vh;
	}

	.first-title {
		position: absolute;
		color: #ffffff;
		left: 40%;
		font-size: 34.7rpx;
		z-index: 100;
	}

	.swiper {
		height: 100%;
	}

	.swiper-image {
		width: 100%;
		height: 100%;
	}

	.swiper-content {
		position: absolute;
		bottom: 320rpx;
		left: 0;
		right: 0;
		text-align: center;
		color: white;
		text-shadow: 0 3.5rpx 17.4rpx rgba(0, 0, 0, 0.3);
	}

	.main-title {
		font-size: 67.7rpx;
		font-family: serif;
		/* font-weight: 700; */
		display: block;
		margin-bottom: 31.2rpx;
	}

	.sub-title {
		font-family: serif;
		font-size: 35rpx;
		opacity: 0.9;
	}

	/* 固定悬浮按钮 */
	.fixed-buttons {
		position: absolute;
		bottom: 120rpx;
		left: 0;
		right: 0;
		display: flex;
		justify-content: center;
		gap: 30rpx;
		padding: 0 40rpx;
	}

	.button {
		background: rgba(0, 0, 0, 0.1);
		border: 1.7rpx solid #ffffff;
		border-radius: 10rpx;
		padding: 20.8rpx 103.4rpx;
		font-size: 24rpx;
		color: #ffffff;
		/* font-weight: 500; */
	}

	/* 指示器 */
	.swiper-dots {
		position: absolute;
		bottom: 85rpx;
		left: 0;
		right: 0;
		display: flex;
		justify-content: center;
		gap: 16rpx;
	}

	.dot {
		width: 52rpx;
		height: 4rpx;
		background: rgba(255, 255, 255, 0.5);
	}

	.dot.active {
		background: white;
		width: 52rpx;
	}

	/* 热门推荐进度条 */
	.progress-container {
		width: 80%;
		height: 8rpx;
		background-color: #e0e0e0;
		border-radius: 4rpx;
		margin: 20rpx auto 30rpx;
		overflow: hidden;
	}

	.progress-bar {
		height: 100%;
		background: linear-gradient(to right, #ff3366, #ff6699);
		border-radius: 4rpx;
		transition: width 0.4s ease;
	}

	/* 通用区域样式 */
	.section {
		margin: 69.4rpx 0;
		padding: 0;
	}

	.section-title {
		display: block;
		text-align: center;
		font-size: 38rpx;
		/* font-weight: 600; */
		color: #333333;
		padding: 34.7rpx 0;
	}

	/* 热门推荐 */
	.horizontal-scroll {
		white-space: nowrap;
		/* padding: 0 52.1rpx; */
		padding-left: 20rpx;
	}

	.product-grid {
		display: flex;
	}

	.product-item {
		width: auto;
		margin-right: 3.5%;
		display: flex;
		flex-direction: column;
		text-align-last: left;
	}

	.product-image {
		width: 365rpx;
		/* height: 451rpx; */
		margin-bottom: 34.7rpx;
	}

	.product-name {
		font-size: 28rpx;
		color: #333333;
		text-align: center;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		width: 100%;
	}

	.product-price {
		font-size: 30rpx;
		color: #000000;
		font-family: math;
		font-weight: 600;
		text-align: center;
		width: 100%;
		margin-top: 13.9rpx;
	}

	/* 共创中心 */
	.creative-grid {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 26rpx;
		padding: 0 52.1rpx;
	}

	.creative-item {
		display: flex;
		flex-direction: column;
	}

	.creative-image {
		width: 100%;
		height: 451rpx;
		margin-bottom: 16rpx;
	}

	.creative-title {
		line-height: 50rpx;
		font-size: 25rpx;
		color: #000000;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		/* width: 100%; */
		max-width: 320rpx;
	}

	.creative-meta {
		display: flex;
		align-items: center;
		/* justify-content: center; */
		gap: 17.4rpx;
		margin-top: 10rpx;
		margin-bottom: 6rpx;
	}

	.avatar {
		width: 48rpx;
		height: 48rpx;
		border-radius: 50%;
		background-color: #ccc;
	}

	.author {
		font-size: 26rpx;
		color: #8c8c8c;
	}

	/* 查看更多按钮 */
	.view-more {
		width: 33%;
		height: 65rpx;
		padding-left: 12rpx;
		border-radius: 10rpx;
		line-height: 64.1rpx;
		text-align: center;
		border: 1rpx solid #787878;
		/* background: #fff; */
		color: #333333;
		margin: 50.3rpx auto;
		font-size: 21.7rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
</style>